/*
 * Copyright (C) 2024 HiHope Open Source Organization.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import createOrGet from '../utils/SingleInstanceHelper';
import { Log } from '../utils/Log';
import { Callback } from '@ohos.base';

const TAG: string = 'DelayTaskManager';

export class DelayTaskManager {
  private taskMap: Map<string, number> = new Map();

  postTask(taskName: string, callback: Callback<void>, delayMs: number) {
    Log.info(TAG, `postTask in, taskName = ${taskName}, delayMs = ${delayMs}`);
    this.cancelTask(taskName);
    this.taskMap.set(taskName, setTimeout(() => {
      Log.info(TAG, `task triggered: ${taskName}`);
      callback && callback();
    }, delayMs));
  }

  cancelTask(taskName: string) {
    Log.info(TAG, `cancel in, taskName = ${taskName}`);
    if (this.taskMap.has(taskName)) {
      try {
        clearTimeout(this.taskMap.get(taskName));
        this.taskMap.delete(taskName);
      } catch (err) {
        Log.error(TAG, `cancel, clearTimeout failed: ${err}, ${JSON.stringify(err)}`);
      }
    }
  }
}

const sDelayTaskManager: DelayTaskManager = createOrGet(DelayTaskManager, 'DelayTaskManager');

export default sDelayTaskManager;